#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
API文档验证脚本

该脚本用于验证生成的API文档的完整性和正确性。
检查文档是否包含所有必要的端点、示例和说明。

使用方法:
    python scripts/validate_api_docs.py

作者: SQL Agent Team
版本: 1.0.0
"""

import os
import re
from pathlib import Path
from typing import List, Dict, Any


class APIDocValidator:
    """API文档验证器"""
    
    def __init__(self, doc_path: str):
        self.doc_path = Path(doc_path)
        self.content = ""
        self.errors = []
        self.warnings = []
        
        # 期望的端点列表
        self.expected_endpoints = [
            {'method': 'GET', 'path': '/'},
            {'method': 'GET', 'path': '/health'},
            {'method': 'POST', 'path': '/sql/query'},
            {'method': 'GET', 'path': '/sql/health'},
            {'method': 'POST', 'path': '/v1/chat/completions'},
        ]
        
        # 期望的数据模型
        self.expected_models = [
            'Message',
            'SqlQueryRequest',
            'SqlQueryResponse',
            'ChatCompletionRequest',
            'ChatCompletionResponse',
        ]
    
    def load_document(self) -> bool:
        """加载文档内容"""
        try:
            if not self.doc_path.exists():
                self.errors.append(f"文档文件不存在: {self.doc_path}")
                return False
            
            with open(self.doc_path, 'r', encoding='utf-8') as f:
                self.content = f.read()
            
            if not self.content.strip():
                self.errors.append("文档内容为空")
                return False
            
            return True
        except Exception as e:
            self.errors.append(f"加载文档时出错: {str(e)}")
            return False
    
    def validate_structure(self) -> None:
        """验证文档结构"""
        required_sections = [
            '# SQL Agent API 接口文档',
            '## 概述',
            '## API 端点',
            '## 数据模型',
            '## 使用示例',
            '## 错误码',
        ]
        
        for section in required_sections:
            if section not in self.content:
                self.errors.append(f"缺少必要章节: {section}")
    
    def validate_endpoints(self) -> None:
        """验证API端点"""
        for endpoint in self.expected_endpoints:
            method = endpoint['method']
            path = endpoint['path']
            
            # 检查端点是否在文档中
            pattern = rf'####\s+{method}\s+{re.escape(path)}'
            if not re.search(pattern, self.content):
                self.errors.append(f"缺少端点文档: {method} {path}")
            
            # 检查是否有请求示例
            if f'curl -X {method}' not in self.content and method == 'GET':
                self.warnings.append(f"端点 {method} {path} 缺少curl示例")
            elif method == 'POST' and 'curl -X POST' not in self.content:
                self.warnings.append(f"端点 {method} {path} 缺少POST请求示例")
    
    def validate_models(self) -> None:
        """验证数据模型"""
        for model in self.expected_models:
            if f'### {model}' not in self.content:
                self.errors.append(f"缺少数据模型文档: {model}")
    
    def validate_examples(self) -> None:
        """验证示例代码"""
        # 检查是否有代码块
        code_blocks = re.findall(r'```[\w]*\n([\s\S]*?)```', self.content)
        
        if len(code_blocks) < 5:
            self.warnings.append("代码示例数量较少，建议增加更多示例")
        
        # 检查是否有Python示例
        if '```python' not in self.content:
            self.warnings.append("缺少Python使用示例")
        
        # 检查是否有JSON示例
        if '```json' not in self.content:
            self.warnings.append("缺少JSON响应示例")
        
        # 检查是否有bash示例
        if '```bash' not in self.content:
            self.warnings.append("缺少bash/curl示例")
    
    def validate_content_quality(self) -> None:
        """验证内容质量"""
        # 检查文档长度
        if len(self.content) < 1000:
            self.warnings.append("文档内容较短，可能缺少详细说明")
        
        # 检查是否有基础URL
        if 'localhost:8013' not in self.content:
            self.warnings.append("文档中缺少基础URL信息")
        
        # 检查是否有错误处理说明
        if '错误码' not in self.content and 'HTTP状态码' not in self.content:
            self.warnings.append("缺少错误码说明")
        
        # 检查是否有版本信息
        if '版本' not in self.content and 'version' not in self.content.lower():
            self.warnings.append("缺少版本信息")
    
    def validate_links_and_references(self) -> None:
        """验证链接和引用"""
        # 检查内部链接（如果有的话）
        internal_links = re.findall(r'\[([^\]]+)\]\(#([^)]+)\)', self.content)
        
        for link_text, anchor in internal_links:
            # 简单检查锚点是否存在对应的标题
            if anchor.replace('-', ' ').lower() not in self.content.lower():
                self.warnings.append(f"可能存在无效的内部链接: {link_text} -> #{anchor}")
    
    def generate_report(self) -> Dict[str, Any]:
        """生成验证报告"""
        return {
            'document_path': str(self.doc_path),
            'document_size': len(self.content),
            'errors': self.errors,
            'warnings': self.warnings,
            'error_count': len(self.errors),
            'warning_count': len(self.warnings),
            'validation_passed': len(self.errors) == 0
        }
    
    def validate(self) -> Dict[str, Any]:
        """执行完整验证"""
        if not self.load_document():
            return self.generate_report()
        
        # 执行各项验证
        self.validate_structure()
        self.validate_endpoints()
        self.validate_models()
        self.validate_examples()
        self.validate_content_quality()
        self.validate_links_and_references()
        
        return self.generate_report()


def print_report(report: Dict[str, Any]) -> None:
    """打印验证报告"""
    print("=" * 60)
    print("API 文档验证报告")
    print("=" * 60)
    print(f"文档路径: {report['document_path']}")
    print(f"文档大小: {report['document_size']} 字符")
    print(f"验证结果: {'✅ 通过' if report['validation_passed'] else '❌ 失败'}")
    print(f"错误数量: {report['error_count']}")
    print(f"警告数量: {report['warning_count']}")
    print()
    
    if report['errors']:
        print("🔴 错误列表:")
        for i, error in enumerate(report['errors'], 1):
            print(f"  {i}. {error}")
        print()
    
    if report['warnings']:
        print("🟡 警告列表:")
        for i, warning in enumerate(report['warnings'], 1):
            print(f"  {i}. {warning}")
        print()
    
    if not report['errors'] and not report['warnings']:
        print("🎉 文档验证完全通过，没有发现任何问题！")
    elif not report['errors']:
        print("✅ 文档验证通过，但有一些建议改进的地方。")
    else:
        print("❌ 文档验证失败，请修复上述错误后重新验证。")


def main():
    """主函数"""
    print("开始验证API文档...")
    
    # 获取项目根目录
    project_root = Path(__file__).parent.parent
    
    # 验证手动编写的文档
    manual_doc_path = project_root / "docs" / "API_Documentation.md"
    generated_doc_path = project_root / "docs" / "API_Documentation_Generated.md"
    
    docs_to_validate = []
    
    if manual_doc_path.exists():
        docs_to_validate.append(("手动编写的文档", manual_doc_path))
    
    if generated_doc_path.exists():
        docs_to_validate.append(("自动生成的文档", generated_doc_path))
    
    if not docs_to_validate:
        print("❌ 没有找到任何API文档文件")
        return
    
    for doc_name, doc_path in docs_to_validate:
        print(f"\n验证 {doc_name}...")
        validator = APIDocValidator(doc_path)
        report = validator.validate()
        print_report(report)
        
        if not report['validation_passed']:
            print(f"\n建议: 请修复 {doc_name} 中的错误")
    
    print("\n验证完成！")


if __name__ == "__main__":
    main()